<!-- src/components/TemplateView.vue -->
<template>
  <v-app>
    <v-container>
      <v-row>
        <v-col cols="12">
          <v-card>
            <v-card-title>
              模板管理
              <v-spacer></v-spacer>
              <v-btn color="primary" @click="openDialog()">
                添加模板
              </v-btn>
            </v-card-title>
            <v-card-text>
              <v-text-field
                  v-model="search"
                  label="搜索模板"
                  class="mb-4"
                  clearable
              ></v-text-field>
              <v-data-table
                  :headers="headers"
                  :items="templates"
                  :loading="loading"
                  :search="search"
                  class="elevation-1"
                  fixed-header
                  density="compact"
              >
                <template v-slot:item.actions="{ item }">
                  <v-icon small @click="deleteItem(item)" class="mr-4">
                    mdi-delete
                  </v-icon>
                  <v-icon small @click="openEditDialog(item)">
                    mdi-pencil
                  </v-icon>
                </template>
              </v-data-table>
            </v-card-text>
          </v-card>
        </v-col>
      </v-row>

      <!-- 编辑对话框 -->
      <v-dialog v-model="dialog" max-width="500px">
        <v-card>
          <v-card-title>
            <span>{{ formTitle }}</span>
          </v-card-title>
          <v-card-text>
            <v-container>
              <v-row>
                <v-col cols="12">
                  <v-text-field
                      v-model="editedItem.name"
                      label="模板名称"
                  ></v-text-field>
                </v-col>
                <v-col cols="12">
                  <v-select
                      v-model="editedItem.package_id"
                      label="请选择音乐包"
                      :items=music_packages
                      item-title="name"
                      item-value="id"
                      variant="outlined"
                  ></v-select>
                </v-col>
                <v-col cols="12">
                  <v-textarea
                      label="模板配置"
                      variant="outlined"
                      v-model="editedItem.detail"
                      auto-grow
                  ></v-textarea>
                </v-col>
              </v-row>
            </v-container>
          </v-card-text>
          <v-card-actions>
            <v-spacer></v-spacer>
            <v-btn color="blue darken-1" text @click="close">取消</v-btn>
            <v-btn color="blue darken-1" text @click="save">保存</v-btn>
          </v-card-actions>
        </v-card>
      </v-dialog>

      <!-- 删除确认对话框 -->
      <v-dialog v-model="dialogDelete" max-width="500px">
        <v-card>
          <v-card-title>确认删除</v-card-title>
          <v-card-text>确定要删除这条模板吗？</v-card-text>
          <v-card-actions>
            <v-spacer></v-spacer>
            <v-btn color="blue darken-1" text @click="closeDelete">取消</v-btn>
            <v-btn color="blue darken-1" text @click="deleteItemConfirm">确认</v-btn>
          </v-card-actions>
        </v-card>
      </v-dialog>
    </v-container>
  </v-app>
</template>

<script>
const API_BASE = import.meta.env.VITE_API_BASE || 'http://106.75.215.61:3000';

export default {
  name: 'TemplateView',
  data: () => ({
    apiBase: API_BASE,
    dialog: false,
    dialogDelete: false,
    loading: false,
    search: '', // 搜索关键词
    music_packages: [],
    // ✅ 改为 Vuetify 3 的写法：title + key
    headers: [
      { title: '模板ID', key: 'id', width: '100px'},
      { title: '模板名称', key: 'name',  width: '120px' },
      { title: '音乐包名称', key: 'package_name',  width: '130px' },
      { title: '模板配置', key: 'detail' },
      { title: '操作', key: 'actions', sortable: false,  width: '90px' }
    ],
    templates: [],
    editedIndex: -1,
    editedItem: {
      id: '',
      name: '',
      detail: '',
      package_id: '',
      package_name: '',
    },
    defaultItem: {
      id: '',
      name: '',
      detail: '',
      package_id: '',
      package_name: '',
    }
  }),

  computed: {
    formTitle() {
      return this.editedIndex === -1 ? '新增模板' : '编辑模板'
    },
  },

  methods: {
    async getAllTemplates() {
      this.loading = true
      try {
        const res = await this.$axios.get(`${this.apiBase}/getAllTemplates`)
        this.templates = res.data
      } catch (e) {
        this.$toast?.error('获取模板列表失败')
      } finally {
        this.loading = false
      }
    },

    async getAllMusicPackages() {
      this.loading = true
      try {
        const res = await this.$axios.get(`${this.apiBase}/getAllMusicPackages`)
        this.music_packages = res.data
      } catch (e) {
        this.$toast?.error('获取音乐包列表失败')
      } finally {
        this.loading = false
      }
    },

    async deleteTemplate(id) {
      this.loading = true
      try {
        const res = await this.$axios.get(`${this.apiBase}/deleteTemplate/` + id)
        if (res.status === 200) {
          this.$toast?.success('删除成功')
        } else {
          throw new Error('删除失败')
        }
      } catch (e) {
        this.$toast?.error('删除失败')
      } finally {
        this.loading = false
      }
    },

    openDialog() {
      this.editedIndex = -1
      this.editedItem = Object.assign({}, this.defaultItem)
      this.dialog = true
    },

    openEditDialog(item) {
      this.editedIndex = this.templates.indexOf(item)
      this.editedItem = Object.assign({}, item)
      this.dialog = true
    },

    deleteItem(item) {
      this.editedIndex = this.templates.indexOf(item)
      this.editedItem = Object.assign({}, item)
      this.dialogDelete = true
    },

    close() {
      this.dialog = false
      this.$nextTick(() => {
        this.editedItem = Object.assign({}, this.defaultItem)
        this.editedIndex = -1
      })
    },

    closeDelete() {
      this.dialogDelete = false
      this.$nextTick(() => {
        this.editedItem = Object.assign({}, this.defaultItem)
        this.editedIndex = -1
      })
    },

    async save() {
      if (!this.editedItem.name || !this.editedItem.detail) {
        this.$toast?.error('模板名称和配置不能为空')
        return
      }

      if (this.editedIndex > -1) {//编辑

        this.loading = true
        try {
          const response = await this.$axios.post(`${this.apiBase}/updateTemplate`, {
            id: this.editedItem.id,
            name: this.editedItem.name,
            package_id: this.editedItem.package_id,
            detail: this.editedItem.detail
          })
          if (response.status !== 200) throw new Error('更新失败')
          this.$toast?.success('更新成功')
          Object.assign(this.templates[this.editedIndex], this.editedItem)
          this.getAllTemplates()
          this.close()
        } catch (e) {
          this.$toast?.error('上传失败')
        } finally {
          this.loading = false
        }
      } else {//新增
        this.loading = true
        try {
          const response = await this.$axios.post(`${this.apiBase}/addTemplate`, {
            name: this.editedItem.name,
            package_id: this.editedItem.package_id,
            detail: this.editedItem.detail,
          })

          if (response.status !== 200) throw new Error('创建失败')

          const { id, name, detail } = response.data.data
          const package_obj = this.music_packages.find(pkg => pkg.id === this.editedItem.package_id);
          const package_name = package_obj ? package_obj.name : '未知包';
          Object.assign(this.editedItem, { id, name, detail, package_name })
          this.$toast?.success('创建成功')

          this.templates.push(this.editedItem)
          this.close()
        } catch (e) {
          this.$toast?.error('上传失败')
        } finally {
          this.loading = false
        }
      }

      this.close()
    },

    async deleteItemConfirm() {
      await this.deleteTemplate(this.editedItem.id)
      this.templates.splice(this.editedIndex, 1)
      this.closeDelete()
    }
  },

  mounted() {
    this.getAllTemplates()
    this.getAllMusicPackages()
  }
}
</script>
